package com.codechuan.didi_hack.utils;

import android.util.Log;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.codechuan.didi_hack.FloatWindowManager;
import com.codechuan.didi_hack.common.Constant;
import com.codechuan.didi_hack.entity.SysCarInfo;
import com.codechuan.didi_hack.entity.SysSuccessOrder;
import com.quickjs.JSContext;
import com.quickjs.QuickJS;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Authenticator;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;

public class DiDiHttpUtil {

    /**
     * @param url 请求地址
     * @Deprecated DD04接口调用
     */
    public static String getDD04(String url, String body) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://106.55.129.131:30000/dd/cal?url=" + url + "&body=" + body)
                .build();
        Response response = null;
        response = okHttpClient.newCall(request).execute();
        return response.body().string();
    }

    // ----------------------------------------登陆开始

    /**
     * @param param
     * @Deprecated 小程序发验证码
     */
    public static String sendCodeWeChatMini(String phone) {
        OkHttpClient client = new OkHttpClient();
        // 封装发码参数
        HashMap<String, Object> hashMapTwo = new HashMap<>();
        hashMapTwo.put("api_version", "1.0.1");
        hashMapTwo.put("appid", 35009);
        hashMapTwo.put("role", 1);
        hashMapTwo.put("extra_info", "{\"channel\":1100000004}");
        hashMapTwo.put("device_name", "Pixel 3");
        String name = "Ny3d38n" + Demo.getRandomAlphanumeric(6) + "UVdBHzEB2HLTUdH8Sl661KCqZvgeewleJZUedUiuxPw98IptM";
        hashMapTwo.put("sec_session_id", name);
        hashMapTwo.put("policy_name_list", new ArrayList<>());
        // 每个账号都是独立的ddfp 需要入数据库
        String ddfp = UUID.randomUUID().toString().replaceAll("-", "");
        hashMapTwo.put("ddfp", ddfp);
        hashMapTwo.put("lang", "zh-CN");
        hashMapTwo.put("wsgenv", "");
        hashMapTwo.put("cell", phone);
        hashMapTwo.put("country_calling_code", "+86");
        hashMapTwo.put("code_type", 0);
        hashMapTwo.put("scene", 1);
        String jsonString = JSONObject.toJSONString(hashMapTwo);
        String encode = URLEncoder.encode(jsonString);
        String xpsid = Demo.getMD5(String.valueOf(Instant.now().toEpochMilli()));
        String param = "lang=zh-CN&token=&access_key_id=9&appversion=6.8.50&channel=1100000004&_ds=&xpsid=" + xpsid + "&xpsid_root" + xpsid + "&q="
                + encode;
        String requestData = param;
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, requestData);
        Request request = new Request.Builder()
                .url("https://epassport.diditaxi.com.cn/passport/login/v5/codeMT?&wsgsig=dd04-opzKIpzv0Helcs8AzeS%2Bt8xv2y9PNdtJ8dTgXCZVc7FBaXDBgRC4W03Plxr%2BQO1c4Kfe0G3mkAAcKH0R%2BgsjrtpZG7%2FQbBGxuzosZsf%2B0iA%2BQVpk5QIdXj6Xe7ArNHch63TcZt3nd9SXNV1a3X7ADt011vcy")
                .addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                .addHeader("accept", "application/json")
                .addHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .addHeader("origin", "https://page.udache.com")
                .addHeader("referer", "https://page.udache.com/driver-biz/driver-recruitment-homepage/index.html?jumpwx=true&usce_channel=24454&usce_sub_channel=129075&delay=1&version=v2&pull_app_version=v2&impression_invoke=false&cost=OCPX&adx=5&lp_type=H5&ad_target=APP&ad_team=WYCSJ&is_haoyue=1&sys_generate=1&product_id=wycsj&strategy_id=&tracking_city_switch=0&account_id=42254723&campaign_id=&event_type=3&bd_vid=10668017544574957152")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "&#34;Windows&#34;")
                .addHeader("sec-fetch-dest", "empty")
                .addHeader("sec-fetch-mode", "cors")
                .addHeader("sec-fetch-site", "cross-site")
                .addHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0")
                .addHeader("Connection", "close")
                .post(body)
                .build();

        Response i_response = null;
        try {
            i_response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(i_response.body().string());
            return jsonObject.getString("error");
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * @Deprecated 小程序发验证码初始化
     */
    public static HashMap<String, String> sendCodeWeChatMiniInit() {
        String md5 = Demo.getMD5(String.valueOf(Instant.now().toEpochMilli()));
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        HashMap<String, Object> hashMap = new HashMap<>();
        long epochMilli = Instant.now().toEpochMilli();
        hashMap.put("lang", "zh-CN");
        hashMap.put("access_key_id", 9);
        hashMap.put("appversion", "6.8.50");
        hashMap.put("channel", 1100000004L);
        hashMap.put("_ds", "");
        hashMap.put("xpsid", md5);
        hashMap.put("xpsid_root", md5);
        hashMap.put("xoid", UUID.randomUUID().toString());
        hashMap.put("xenv", "wxmp");
        hashMap.put("prod_key", "ut-aggre-homepage");
        hashMap.put("_type", "product");
        hashMap.put("_t", epochMilli);
        hashMap.put("need_page_config", false);
        RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(hashMap));
        String url = "https://api.didi.cn/webx/mp/product/init?_t=" + String.valueOf(epochMilli);
        try {
            url = url + "&wsgsig=" + URLEncoder.encode(getDD04(url, ""));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 创建请求对象，并添加自定义的请求头
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Host", "api.didi.cn")
                .addHeader("Connection", "keep-alive")
                .addHeader("secdd-authentication", String.valueOf(epochMilli))
                .addHeader("charset", "utf-8")
                .addHeader("didi-header-rid", String.valueOf(epochMilli))
                .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 12; Pixel 3 Build/SP1A.210812.016.C2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/122.0.6261.120 Mobile Safari/537.36 XWEB/1220067 MMWEBSDK/20240404 MMWEBID/3880 MicroMessenger/8.0.49.2600(0x28003156) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android")
                .addHeader("x-cluster-id", "786")
                .addHeader("content-type", "application/json")
                .addHeader("Accept-Encoding", "gzip,compress,br,deflate")
                .addHeader("secdd-challenge", "3|v1.1.0||||||")
                .addHeader("didi-header-hint-content", "{\"lang\":\"zh-CN\",\"Cityid\":0")
                .addHeader("Referer", "https://servicewechat.com/wxaf35009675aa0b2a/866/page-frame.html")
                .build();

        // 发送请求并获取响应
        Response response = null;
        try {
            response = client.newCall(request).execute();
            assert response.body() != null;
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            response.headers();
            System.out.println("s");
            return null;
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * @param phone   手机号
     * @param code    验证码
     * @param account 账户/卡密
     * @return 返回发送结果
     * @Deprecated 滴滴微信小程序登录
     */
    public static String loginDiDi(String phone, String code) {
        // 初始化
        sendCodeWeChatMiniInit();

        String md5 = Demo.getMD5(String.valueOf(Instant.now().toEpochMilli()));
        String ddfp = UUID.randomUUID().toString().replaceAll("-", "");
        DiDiHttpUtil diDiHttpUtil = new DiDiHttpUtil();
        Map<String, String> header = new HashMap<>();
        header.put("Host", "epassport.diditaxi.com.cn");
        header.put("secdd-authentication", "");
        header.put("charset", "utf-8");
        header.put("mpxlogin-ver", "5.4.30");
        header.put("didi-header-rid", Demo.getMD5(String.valueOf(Instant.now().toEpochMilli())));
        header.put("User-Agent", "Mozilla/5.0 (Linux; Android 12; Pixel 3 Build/SP1A.210812.016.C2; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/122.0.6261.120 Mobile Safari/537.36 XWEB/1220067 MMWEBSDK/20240404 MMWEBID/3880 MicroMessenger/8.0.49.2600(0x28003156) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android");
        header.put("content-type", "application/x-www-form-urlencoded");
        header.put("secdd-challenge", " 3|v1.1.0||||||");
        header.put("didi-header-hint-content", " {\"lang\":\"zh-CN\",\"Cityid\":173}");
        header.put("Referer", " https://servicewechat.com/wxaf35009675aa0b2a/866/page-frame.html");
        String param = "lang=zh-CN&token=&access_key_id=9&appversion=6.8.50&channel=1100000004&_ds=&xpsid=" + md5 +
                "&xpsid_root=" + md5 +
                "&q=%7B%22api_version%22:%221.0.1%22,%22appid%22:35009,%22role%22:1,%22extra_info%22:%7B%22channel%22:1100000004%7D,%22device_name%22:%22Pixel%203%22,%22sec_session_id%22:%22tpZmRquXk" + Demo.getRandomAlphanumeric(6) +
                "vZtNd5ZHuSPwrfNnGz8PwSZVsX7XxrTqIOy07VSpvFYnlzabL%22,%22policy_id_list%22:[50001289],%22policy_name_list%22:[],%22ddfp%22:%22" +
                ddfp + "%22,%22lang%22:%22zh-CN%22,%22wsgenv%22:%22%22,%22cell%22:%22" + phone + "%22,%22country_calling_code%22:%22%2B86%22,%22code%22:%22"
                + code + "%22,%22oauthcode%22:%220c3XXD000ckUeS12Ry2005lhTb1XXD0l%22%7D";
        String s = null;
        try {
            s = diDiHttpUtil.weChatMiniLogin("https://epassport.diditaxi.com.cn/passport/login/v5/signInByCode?wsgsig=dd03-HXijLaL4nkBdbIaGeUGg9VPNVdrbgSqCg%2FzGEUdIVdrcbOdJFdfc9e61kUBcb26Aa9v8cFI7llL9ELa5ekiealIBkk29GId9eUvGa%2FM1lkk09IM1AauJaqe8khA", param, header);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject jsonObject = JSONObject.parseObject(s);
        // todo 数据库需要存入 ddfp ticket 手机号

        return jsonObject.getString("error");
    }

    /**
     * @Deprecated 微信小程序登录获取token
     */
    public String weChatMiniLogin(String url, String param, Map<String, String> header) throws UnsupportedEncodingException, IOException {
        OutputStreamWriter out;
        BufferedReader in = null;
        String result = "";
        URL realUrl = new URL(url);
        // 打开和URL之间的连接
        HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
        //设置超时时间
        conn.setConnectTimeout(5000);
        conn.setReadTimeout(15000);
        // 设置通用的请求属性
        if (header != null) {
            for (Map.Entry<String, String> entry : header.entrySet()) {
                conn.setRequestProperty(entry.getKey(), entry.getValue());
            }
        }
        conn.setRequestMethod("POST");
        conn.addRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        // 发送POST请求必须设置如下两行
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // 获取URLConnection对象对应的输出流
        out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");// utf-8编码
        // 发送请求参数
        out.write(param);

        // flush输出流的缓冲
        out.flush();
        // 定义BufferedReader输入流来读取URL的响应
        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf8"));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
        if (out != null) {
            out.close();
        }
        if (in != null) {
            in.close();
        }
        return result;
    }
    // ----------------------------------------登陆结束


    // ----------------------------------------刷单开始

    /**
     * @Deprecated 获取滴滴城际和市内刷单
     */
    public static void getACrossCityOrderInTheLobby(int size) throws IOException {
        System.out.println("开始启动 ----->Token是" + Constant.token.get(size));
        OkHttpClient client = new OkHttpClient();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("access_key_id", 2);
        hashMap.put("route_id", 0); //城际和市内刷单置0 //行程和常用 行程ID 或 常用路线ID  route_id 传过来 注意长整数精度丢失 导致出错
        hashMap.put("app_version", "6.9.8");
        hashMap.put("ddfp", "8f344f7d242546b2a2b26a61a49d2d99");// imei 每个账号对一个ime
        hashMap.put("lng", 113.269073);
        hashMap.put("address_select", new String[0]);
        hashMap.put("session_id", 0);
        HashMap<String, Object> city_center = new HashMap<>();
        city_center.put("lat", 23.363454);
        city_center.put("lng", 113.269073);
        hashMap.put("city_center", city_center);
        hashMap.put("token", URLEncoder.encode(Constant.token.get(size)));
        hashMap.put("sort_type", "smart_sort"); // 排序方式  //智能排序 smart_sort //最高 price_sort //最近 distance_sort //最早 distance_sort
        hashMap.put("city_name", "广州市");
        hashMap.put("tab_id", 2); // 1=市内 2=跨城 3=常用
        hashMap.put("filter_group", new String[0]);
        hashMap.put("page_index", 0);
        hashMap.put("to_city_id", 0);
        hashMap.put("lat", 23.363454);
        hashMap.put("city_id", 3);
        // 创建请求对象，并添加自定义的请求头
        String bodyString = JSONObject.toJSONString(hashMap);
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, bodyString);
        // 判断大厅的dd04是否存在 不存在则获取 存在则复用 直到用户重新点抢单按钮进行置空获取最新请求参数
        if (Constant.DT_DD04 == null)
            Constant.DT_DD04 = getDD04(URLEncoder.encode("https://api.udache.com/gulfstream/hermesapi/v2/driver/dBusinessOrderList"), URLEncoder.encode(bodyString));
        Request request = new Request.Builder()
                .url("https://api.udache.com/gulfstream/hermesapi/v2/driver/dBusinessOrderList")
                .post(body)
                .addHeader("ticket", Constant.token.get(size))
                .addHeader("didi-header-omgid", Demo.getMD5(String.valueOf(Instant.now().toEpochMilli())))
                .addHeader("didi-header-ssuuid", UUID.randomUUID().toString().replace("-", ""))
                .addHeader("secdd-authentication", Constant.DT_SE_CDD_AUTHENTICATION)
                .addHeader("Productid", "0")
                .addHeader("secdd-challenge", Constant.DT_SE_CDD_CHALLENGE)
                .addHeader("Content-Type", "application/json;charset=UTF-8")
                .addHeader("Host", "api.udache.com")
                .addHeader("TripCountry", "CN")
                .addHeader("wsgsig", Constant.DT_DD04)
                .addHeader("didi-header-rid", UUID.randomUUID().toString().replace("-", ""))
                .addHeader("CityId", "3")
                .addHeader("User-Agent", "com.sdu.didi.psnger/6.9.8 Rabbit/1.3.22 Carrot/1.4.28")
                .addHeader("didi-httpdns", "1")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 发送请求并获取响应
                response = client.newCall(request).execute();
                if (response == null)
                    return;
                JSONObject jsonObject = null;
                try {
                    jsonObject = JSONObject.parseObject(response.body().string());
                } catch (Exception e) {
                    System.out.println(Constant.format.format(new Date() + "大厅刷新异常"));
                    return;
                }
                // 获取响应头
                String authentication = response.header("secdd-authentication");
                if (authentication != null && !authentication.isEmpty()) {
                    Constant.DT_SE_CDD_AUTHENTICATION = authentication;
                }
                String sessionid = response.header("set-secch-sessionid");
                if (sessionid != null && !sessionid.isEmpty()) {
                    String pattern = "(?<=secch_sessionid=)[0-9a-m]+"; // 正则表达式
                    Pattern p = Pattern.compile(pattern);
                    Matcher m = p.matcher(sessionid);
                    if (m.find()) {
                        Constant.DT_SE_CDD_CHALLENGE = "1,com.sdu.didi.psnger|1.0.28||||0||" + m.group();
                    }
                }
                JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
                String code = jsonObject.getString("code");
                if (code != null && code.equals("0")) {
                    String func_def = data.getString("func_def");
                    String func = data.getString("func");
                    String args = data.getString("args");
                    String chid = data.getString("chid");
                    String ts = data.getString("ts");
                    String res = Demo.executeJs(func_def, Demo.extractFunctionName(func_def), args);
                    Constant.DT_SE_CDD_CHALLENGE = "1,com.sdu.didi.psnger|1.0.28" + "|" + func + "|" + args + "|" + ts + "|" + res + "|" + chid + "|";
                    getACrossCityOrderInTheLobby(size);
                } else {
                    System.out.println("接口");
                    if (jsonObject.getString("errno") != null && jsonObject.getString("errno").equals("5555555")) {
                        Log.i(Constant.token.get(size) + "大厅刷订单过快", "大厅刷订单过快");
                    } else {
                        if (jsonObject.getString("errno").equals("5550002")) {
                            System.out.println("该账号不是司机号");
                            return;
                        }
                        JSONArray jsonArray = data.getJSONArray("passenger_cards");
                        if (jsonArray.size() <= 0) {
                            return;
                        }
                        FloatWindowManager.get().addLog("大厅获取到:" + jsonArray.size());
                        for (Object passengerCards : jsonArray) {
                            JSONObject listData = JSONObject.parseObject(passengerCards.toString());
                            JSONObject invite_params = listData.getJSONObject("invite_button").getJSONObject("invite_params");
                            // 接单需要的行程id
                            String routeId = invite_params.getString("route_id");
                            // 接单需要的key
                            String group_key = invite_params.getString("group_key");
                            // 接单需要的经纬度
                            String from_lat = invite_params.getString("from_lat");
                            String from_lng = invite_params.getString("from_lng");
                            String to_lat = invite_params.getString("to_lat");
                            String to_lng = invite_params.getString("to_lng");
                            String from_address = invite_params.getString("from_address");
                            String starting_poi_id = invite_params.getString("starting_poi_id");
                            String sess_id = invite_params.getString("sess_id");
                            String from_source = invite_params.getString("from_source");
                            String from_city_id = invite_params.getString("from_city_id");
                            JSONObject orderInfo = listData.getJSONObject("order_info");
                            // 出发位置 广州市·焕新医疗美容
                            String from_name = orderInfo.getString("from_name");
                            // 终点位置 深圳市·深圳金福林酒店
                            String to_name = orderInfo.getString("to_name");
                            // 距离乘客距离 0.9km
                            String from_dist = orderInfo.getString("from_dist");
                            // 接单需要的orderId
                            String oid = orderInfo.getString("oid");

                            JSONArray tag_list = listData.getJSONArray("tag_list");

                            // 拼单或独享 {"text":"{1人愿拼}"}
                            String pcDxString = Demo.extractContent(JSONObject.parseObject(tag_list.getString(0)).getString("text"));

                            // 订单里程 {"text":"订单里程132.7km"}
                            String order_des = tag_list.getString(1);
                            order_des = JSONObject.parseObject(tag_list.getString(1)).getString("text");
                            String replace = order_des.replaceAll("订单里程", "").replace("km", "");

                            // 出发时间 明天{00:20-00:35}
                            String start_date = listData.getJSONObject("time_range").getString("start_date");
                            // 价格
                            String price = listData.getJSONObject("price_info").getString("title");
                            price = Demo.extractContent(price).replaceAll("元", "");

                            System.out.println("订单是:" + "\t出发位置是:" + from_name + "\t终点位置是:" + from_dist + "\t订单类型是:" + pcDxString + "\t订单总公里数是:" + replace + "\t订单价格是:" + price);

                            // 封装订单信息
                            SysSuccessOrder sysSuccessOrder = new SysSuccessOrder();
                            sysSuccessOrder.setOrderId(oid);
                            sysSuccessOrder.setGroupKey(group_key);
                            sysSuccessOrder.setRouteId(null);
                            sysSuccessOrder.setLat(from_lat);
                            sysSuccessOrder.setLng(from_lng);
                            sysSuccessOrder.setToLat(to_lat);
                            sysSuccessOrder.setRouteId(routeId);
                            sysSuccessOrder.setToLng(to_lng);
                            sysSuccessOrder.setFromCityId(from_city_id);
                            sysSuccessOrder.setStartingPoiId(starting_poi_id);
                            sysSuccessOrder.setFromName(from_name);
                            sysSuccessOrder.setFromSource(from_source);
                            sysSuccessOrder.setSessId(sess_id);
                            sysSuccessOrder.setFromAddress(from_address);
                            sysSuccessOrder.setOrderDes(order_des);
                            sysSuccessOrder.setPrice(price);
                            sysSuccessOrder.setOrderType("大厅");
                            sysSuccessOrder.setTicket(Constant.token.get(size));
                            sysSuccessOrder.setSysCarInfo(Constant.CAR_INFO);
                            // 获取订单时间
                            String orderSetUpTime = getOrderSetUpTime(Constant.token.get(size), sysSuccessOrder, "8f344f7d242546b2a2b26a61a49d2d99");
                            if (orderSetUpTime == null)
                                return;
                            // 执行抢单逻辑
                            invitePeersCrossCity(sysSuccessOrder, orderSetUpTime, Constant.token.get(size), "8f344f7d242546b2a2b26a61a49d2d99");
                        }
                    }
                }

            }
        });


    }

    /**
     * @Deprecated 获取滴滴取行程订单
     */
    public static void getXcOrderList(String route_id, String ddfp, int tokenNumber) throws IOException {
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(Constant.token.get(tokenNumber));
        String url = "https://api.udache.com/gulfstream/hermesapi/v2/driver/dSfcDriverList?session_id=0&route_id=" + route_id
                + "&page_type=&page_index=0&session_id=0&access_key_id=2&app_version=6.9.8&ddfp=" + ddfp + "&token=" + token;

        try {
            if (Constant.XC_DD04 == null) {
                Constant.XC_DD04 = getDD04(URLEncoder.encode(url), "");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("ticket", Constant.token.get(tokenNumber));
        headers.put("didi-header-omgid", Demo.getRandomAlphanumeric(22));
        headers.put("didi-header-ssuuid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("authentication", Constant.XC_SE_CDD_AUTHENTICATION);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", Constant.XC_SE_CDD_CHALLENGE);
        headers.put("Host", "api.udache.com");
        headers.put("Connection", "Keep-Alive");
        headers.put("TripCountry", "CN");
        headers.put("wsgsig", Constant.XC_DD04);
        headers.put("didi-header-rid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("CityId", "3");
        headers.put("User-Agent", "com.sdu.didi.psnger/6.8.12 Rabbit/1.2.6.5 Carrot/1.3.5");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);

        // 构建完整的请求
        Request request = requestBuilder.build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = null;
            try {
                jsonObject = JSONObject.parseObject(response.body().string());
            } catch (Exception e) {
                Log.i("大厅刷新异常", "大厅刷新异常");
                return;
            }
            //  获取响应头
            String authentication = response.header("secdd-authentication");
            if (authentication != null && !authentication.isEmpty()) {
                Constant.XC_SE_CDD_AUTHENTICATION = authentication;
            }
            String sessionid = response.header("set-secch-sessionid");
            if (sessionid != null && !sessionid.isEmpty()) {
                String pattern = "(?<=secch_sessionid=)[0-9a-m]+"; // 正则表达式
                Pattern p = Pattern.compile(pattern);
                Matcher m = p.matcher(sessionid);
                if (m.find()) {
                    Constant.XC_SE_CDD_CHALLENGE = "1,com.sdu.didi.psnger|1.0.28||||0||" + m.group();
                }
            }

            JSONObject data = JSONObject.parseObject(jsonObject.getString("data"));
            String code = jsonObject.getString("code");

            if (code != null && code.equals("0")) {
                String func_def = data.getString("func_def");
                String func = data.getString("func");
                String args = data.getString("args");
                String chid = data.getString("chid");
                String ts = data.getString("ts");
                String res = Demo.executeJs(func_def, Demo.extractFunctionName(func_def), args);
                Constant.XC_SE_CDD_CHALLENGE = "1,com.sdu.didi.psnger|1.0.28" + "|" + func + "|" + args + "|" + ts + "|" + res + "|" + chid + "|";
                getXcOrderList(route_id, ddfp, tokenNumber);
            } else {
                if (jsonObject.getString("errno") != null && jsonObject.getString("errno").equals("5555555")) {
                    Log.i(token + "大厅刷订单过快", "大厅刷订单过快");
                } else {
                    for (Object passengerCards : data.getJSONArray("passenger_cards")) {
                        JSONObject listData = JSONObject.parseObject(passengerCards.toString());
                        JSONObject invite_params = listData.getJSONObject("invite_button").getJSONObject("invite_params");
                        String string = invite_params.getString("route_id");
                        String group_key = invite_params.getString("group_key");
                        String from_lat = invite_params.getString("from_lat");
                        String from_lng = invite_params.getString("from_lng");
                        String to_lat = invite_params.getString("to_lat");
                        String to_lng = invite_params.getString("to_lng");
                        String from_address = invite_params.getString("from_address");
                        String starting_poi_id = invite_params.getString("starting_poi_id");
                        String sess_id = invite_params.getString("sess_id");
                        String from_source = invite_params.getString("from_source");
                        String from_city_id = invite_params.getString("from_city_id");


                        JSONObject orderInfo = listData.getJSONObject("order_info");
                        String from_name = orderInfo.getString("from_name");
                        String to_name = orderInfo.getString("to_name");
                        String from_dist = orderInfo.getString("from_dist");
                        String oid = orderInfo.getString("oid");

                        JSONArray tag_list = listData.getJSONArray("tag_list");
                        String pc_dx = tag_list.getString(0);
                        String order_des = tag_list.getString(1);

                        String start_date = listData.getJSONObject("time_range").getString("start_date");
                        String price = listData.getJSONObject("price_info").getString("title");

                        System.out.println("行程订单类型:" + pc_dx + "\t订单价格:" + price + "\t订单里程:" + order_des + "\t订单时间:" + start_date);
                    }
                    FloatWindowManager.get().addLog(Constant.format.format(new Date()) + "大厅刷新订单:" + data.getJSONArray("passenger_cards").size());

                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    // ----------------------------------------刷单结束

    // ----------------------------------------接单开始

    /**
     * @param ticket          接单号的ticket
     * @param sysSuccessOrder 订单实体类
     * @return
     * @Deprecated 获取订单时间
     */
    public static String getOrderSetUpTime(String ticket, SysSuccessOrder sysSuccessOrder, String ddfp) {
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String url = "https://api.udache.com/gulfstream/driver-center/v1/dGetTimePicker?to_lat="
                + sysSuccessOrder.getToLat() + "&from_lng=" + sysSuccessOrder.getLng() + "&to_lng=" + sysSuccessOrder.getToLng()
                + "&scenes_type=driver_invite_detail&oid=" + sysSuccessOrder.getOrderId() + "&from_lat=" + sysSuccessOrder.getLat()
                + "&access_key_id=2&app_version=6.8.12&ddfp=" + ddfp + "&token=" + URLEncoder.encode(ticket);
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);
        Request request = requestBuilder.build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONObject data = jsonObject.getJSONObject("data");
            return data.getString("from_date_stamp");
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * @param order     订单实体类
     * @param setUpTime 订单时间
     * @param auth      授权信息 使用刷单时候的auth
     * @param challenge js算法 使用刷单时候的challenge
     * @Deprecated 邀请同行_跨城
     */
    public static JSONObject invitePeersCrossCity(SysSuccessOrder order,
                                                  String setUpTime,
                                                  String ticket,
                                                  String ddfp) {
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String url = "https://api.udache.com/gulfstream/hermesapi/v2/driver/dBusinessInvite?setup_time=" + setUpTime +
                "&from_city_id=" + order.getFromCityId() + "&starting_poi_id=" + order.getStartingPoiId() +
                "&have_friend=0" + "&extra_params=&route_id=" + order.getRouteId() + "&lng=" + String.valueOf(order.getLng()) +
                "&ddfp=" + ddfp + "&from_lng=" + order.getLng() + "&degree=50&channel=15&oid=" + order.getOrderId() +
                "&type=2&from_name=" + URLEncoder.encode(order.getFromName()) + "&from_source=" + order.getFromSource() +
                "&seat_count=4&sess_id=" + order.getSessId() + "&gvid=" + order.getSysCarInfo().getgVid() + "&from_address=" +
                URLEncoder.encode(order.getFromAddress()) + "&lat=" + String.valueOf(order.getLat()) + "&group_key=" + order.getGroupKey() +
                "&from_lat=" + order.getLat() + "&access_key_id=2&app_version=6.9.8&token=" + URLEncoder.encode(ticket);
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);
        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("ticket", ticket);
        headers.put("didi-header-omgid", Demo.getRandomAlphanumeric(22));
        headers.put("didi-header-ssuuid", UUID.randomUUID().toString().replaceAll("-", ""));
        headers.put("secdd-authentication:", Constant.DT_SE_CDD_AUTHENTICATION);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", Constant.DT_SE_CDD_CHALLENGE);
        headers.put("didi-header-hint-content", "{\"app_timeout_ms\":27000, \"utc_offset\":\"480\",\"location_cityid\":26," +
                "\"Cityid\":" + order.getFromCityId() + ",\"lang\":\"zh-CN\",\"locale\":\"zh-CN\"}");
        headers.put("TripCountry", "CN");
        headers.put("wsgsig", dd04);
        headers.put("didi_header_rid", UUID.randomUUID().toString().replaceAll("-", ""));
        headers.put("CityId", order.getFromCityId());
        headers.put("User-Agent", "com.sdu.didi.psnger/6.9.8 Rabbit/1.3.22 Carrot/1.4.28");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);
        // 构建完整的请求
        Request request = requestBuilder.build();
        System.out.println("订单时间是:" + setUpTime + "\t执行大厅抢单的是:" + order);
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            return jsonObject.getJSONObject("data");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * @param order     订单实体类
     * @param setUpTime 订单时间
     * @param auth      授权信息
     * @param challenge js算法
     * @Deprecated 邀请同行_行程
     */
    public JSONObject invitePeersItinerary(SysSuccessOrder order,
                                           String setUpTime,
                                           String ticket,
                                           String auth,
                                           String ddfp,
                                           String challenge) {

        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String url = "https://api.udache.com/gulfstream/hermesapi/v2/driver/dInviteCreate?setup_time=" + setUpTime + "&extra_params=&route_id=" +
                order.getRouteId() + "&lng=" + order.getLng() + "&oid=" + order.getOrderId() + "&type=2&lat=" + order.getLat() +
                "&group_key=" + order.getGroupKey() + "&access_key_id=2&app_version=6.8.12&ddfp=" + ddfp + "&token=" + URLEncoder.encode(token);
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);
        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("ticket", ticket);
        headers.put("didi-header-omgid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("didi-header-ssuuid", ddfp);
        headers.put("secdd-authentication:", Constant.XC_SE_CDD_AUTHENTICATION);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", Constant.XC_SE_CDD_CHALLENGE);
        headers.put("wsgsig", dd04);
        headers.put("CityId", "26");
        headers.put("User-Agent", "com.sdu.didi.psnger/6.8.12 Rabbit/1.2.6.5 Carrot/1.3.5");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);
        // 构建完整的请求
        Request request = requestBuilder.build();
        System.out.println("订单时间是:" + setUpTime + "\t执行行程抢单的是:" + order);
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            return jsonObject.getJSONObject("data");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    // ----------------------------------------接单结束


    // ----------------------------------------其它滴滴接口开始

    /**
     * @Deprecated 获取自己发布的行程列表
     */
    public static void getMyScList() {
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(Constant.token.get(0));
        String url = "https://api.udache.com/gulfstream/driver-center/v1/dGetSFCHistoryOrderV2?nginx_cors=false&token=" + token
                + "&city_id=3&access_key_id=2&user_role=2&app_version=6.8.12&year=&month=";
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        url = url + "&wsgsig=" + URLEncoder.encode(dd04);
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("Host", "api.udache.com");
        headers.put("Connection", "keep-alive");
        headers.put("Accept", "application/json, text/plain, */*");
        headers.put("Origin", "https://page.udache.com");
        headers.put("User-Agent", "Mozilla/5.0 (Linux; Android 8.1.0; Redmi 5 Build/OPM1.171019.026; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/71.0.3578.99 Mobile Safari/537.36 didi.passenger/6.8.12 FusionKit/2.0.0  OffMode/0");
        headers.put("Accept-Language", "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7");
        headers.put("X-Requested-With", "com.sdu.didi.psnger");
        headers.forEach(requestBuilder::addHeader);

        // 构建完整的请求
        Request request = requestBuilder.build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONObject data = jsonObject.getJSONObject("data");
            JSONObject routeCardList = data.getJSONObject("route_card_list");
            JSONArray underwayList = routeCardList.getJSONArray("underway_list");
            for (Object o : underwayList) {
                JSONObject underway = JSONObject.parseObject(o.toString());
                Object order_card_list = underway.getJSONArray("order_card_list").get(0);
                JSONObject orderInfo = JSONObject.parseObject(order_card_list.toString()).getJSONObject("order_info");
                JSONObject status_info = JSONObject.parseObject(order_card_list.toString()).getJSONObject("status_info");

                String route_id = underway.getString("route_id");
                String from_name = orderInfo.getString("from_name");
                String to_name = orderInfo.getString("to_name");
                String show_time = orderInfo.getString("show_time");
                String sub_title = status_info.getString("sub_title");
                System.out.println("ok");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param ticket    token
     * @param auth      用户认证信息
     * @param challenge js算法
     * @Deprecated 取司机车辆信息
     */
    public static SysCarInfo getDriverVehicleInformation(String ticket) {
        OkHttpClient client = new OkHttpClient();
        String token = URLEncoder.encode(ticket);
        String url = "https://api.udache.com/gulfstream/driver-center/v1/dGetCarListConfig?access_key_id=2&app_version=6.8.12&ddfp="
                + UUID.randomUUID().toString().replace("-", "") + "&token=" + URLEncoder.encode(ticket);
        String dd04;
        try {
            dd04 = getDD04(URLEncoder.encode(url), "");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);

        // 添加自定义请求头
        Map<String, String> headers = new HashMap<>();
        // js算法结果
        String secdd_challenge = "1,com.sdu.didi.psnger|1.0.28||||0||";
        // 认证信息
        String secdd_authentication = "c9b8d7050edfdbda045b14aa7b5d4db484ec7abb1fc410d6b830385e4199d4e721eb3ed4272eb36b32a9d8887eee556a27437a569101000001000000";

        headers.put("ticket", ticket);
        headers.put("didi-header-omgid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("didi-header-ssuuid", UUID.randomUUID().toString().replace("-", ""));
        headers.put("secdd-authentication:", secdd_authentication);
        headers.put("Productid", "0");
        headers.put("secdd-challenge", secdd_challenge);
        headers.put("didi-header-hint-content", "{\"app_timeout_ms\":3000, \"utc_offset\":\"480\",\"location_cityid\":26," +
                "\"Cityid\":26,\"lang\":\"zh-CN\",\"locale\":\"zh-CN\"}");
        headers.put("TripCountry", "CN");
        headers.put("wsgsig", dd04);
        headers.put("didi_header_rid", Demo.getMD5(String.valueOf(Instant.now().toEpochMilli())));
        headers.put("CityId", "26");
        headers.put("User-Agent", "com.sdu.didi.psnger/6.8.12 Rabbit/1.2.6.5 Carrot/1.3.5");
        headers.put("didi-httpdns", "1");
        headers.forEach(requestBuilder::addHeader);
        // 构建完整的请求
        Request request = requestBuilder.build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray jsonArray;
            try {
                jsonArray = jsonObject.getJSONObject("data").getJSONArray("car_list");
            } catch (Exception e) {
                return null;
            }
            for (Object o : jsonArray) {
                JSONObject listData = JSONObject.parseObject(o.toString());
                String text = listData.getString("text");
                String gvid = listData.getString("gvid");
                String maxSeatNum = listData.getString("max_seat_num");
                SysCarInfo sysCarInfo = new SysCarInfo();
                sysCarInfo.setText(text);
                sysCarInfo.setgVid(gvid);
                sysCarInfo.setMaxSeatNum(maxSeatNum);
                return sysCarInfo;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    // ----------------------------------------其它滴滴接口结束


}